import { getOpenId, uploadFile, uploadPath, employeeImportFile, staffImportDownload } from '@/api/park/employeeManagement'
import config from '@/common/config'

// 扫码
export function getScan(onlyCamera, onSuccess, onFail) {
	uni.scanCode({
		onlyFromCamera: onlyCamera,
		success(res) {
			onSuccess(res)
		},
		fail(err) {
			onFail(err)
		}
	})
}

// 授权 - 获取授权设置信息
export function getSetting(auth, onSuccess, onFail) {
	uni.getSetting({
		success(res) {
			if (res.authSetting[`scope.${auth}`]) {
				onSuccess(res)
			} else {
				onFail(res)
			}
		},
		fail(err) {
			console.log('uniapi异常')
		}
	})
}

// 登录授权 - 检查授权
export function uniCheckSession(onSuccess, onFail, onComplete) {
	uni.checkSession({
		provider: 'weixin',
		success(res) {
			onSuccess(res)
		},
		fail(err) {
			onFail(err)
		},
		complete(c) {
			onComplete(c)
		}
	})
}

// 登录授权 - 第一步 - 微信登录获取code
export function uniLogin(onSuccess, onFail) {
	uni.login({
		provider: 'weixin',
		success(res) {
			const { code } = res
			if (code) {
				onSuccess(code)
			} else {
				onFail(res)
			}
		},
		fail(err) {
			console.log('uniapi异常')
		}
	})
}

// 登录授权 - 第二步 - 获取用户信息
export function uniGetUserData(desc, onSuccess, onFail) {
	uni.getUserProfile({
		provider: 'weixin',
		desc: desc,
		success(res) {
			if (res.errMsg == 'getUserProfile:ok') {
				onSuccess(res)
			} else {
				onFail(res)
			}
		},
		fail(err) {
			console.log('uniapi异常')
			console.log(err)
		}
	})
}

// 消息模板
export function getMessageAuthorize(tmplIds, onSuccess, onFail) {
	uni.requestSubscribeMessage({
		tmplIds,
		success(res) {
			onSuccess(res)
		},
		fail(err) {
			onFail(err)
		}
	})
}

// 获取定位信息
export function getLocation(onSuccess, onFail) {
	uni.getLocation({
		type: 'gcj02',
		success(res) {
			onSuccess(res)
		},
		fail(err) {
			onFail(err)
		}
	})
}

// 设置存储
export function setStorageSync(key, val) {
	uni.setStorageSync(key, val)
}

// 获取存储
export function getStorageSync(key) {
	return uni.getStorageSync(key)
}

// 显示加载
export function showLoading(title) {
	return uni.showLoading({
		title: title || '加载中...',
		mask: true
	})
}

// 隐藏加载
export function hideLoading() {
	return uni.hideLoading()
}

// 显示toast
export function showToast(title, icon, duration = 1500) {
	uni.showToast({
		title,
		icon: icon || 'success',
		duration: duration
	})
}
// 显示对话框
export function showModal(options) {
	uni.showModal(options)
}

// 菜单权限的跳转
export function navigateTo(url) {
	let path = url
	const menuList = uni.getStorageSync('menuList')
	let i = path.indexOf('?')
	if (i > -1) {
		path = path.substr(0, i)
	}
	if (menuList.indexOf(path) == '-1') {
		uni.showToast({
			title: '您无此操作权限',
			icon: 'none',
			duration: 1000
		})
	} else {
		// 匹配路径
		uni.navigateTo({
			url
		})
	}
}

// 菜单token的跳转
export function navigateToCheckToken(url) {
	let accessToken = uni.getStorageSync('accessToken')
	if (!accessToken) {
		showModal({
			title: '登录',
			content: '该功能需要登录, 立即去登录',
			showCancel: true,
			confirmText: '去登录',
			success: res => {
				if (res.confirm) {
					uni.navigateTo({
						url: `/pages/my/login`
					})
				} else if (res.cancel) {

				}
			}
		})
		return
	}

	uni.navigateTo({
		url: url
	})
}


/**认证跳转*/
export function navigateToCertificationJump() {
	uni.showModal({
		title: '您还未认证，请先认证',
		content: '是否去认证?',
		success(res) {
			if (res.confirm) {
				uni.navigateTo({
					url: `/pages/parkEnterprise/enterprise/certification`
				})
			} else {
				return
			}
		}
	})
}

/**是否登录或者登录过期*/
export function navigateToLoginExpired() {
	let tenantId = uni.getStorageSync('TENANT_ID')
	let content = ''
	if (tenantId) {
		content = '登录过期, 立即去登录'
	} else {
		content = '该功能需要登录, 立即去登录'
	}

	showModal({
		title: '登录',
		content,
		showCancel: true,
		confirmText: '去登录',
		success: res => {
			if (res.confirm) {
				uni.navigateTo({
					url: `/pages/park/login/index`
				})
			} else if (res.cancel) {

			}
		}
	})

}

/**是否登录或者登录过期*/
export function navigateToLogin() {
	showModal({
		title: '登录',
		content: '立即去登录',
		showCancel: true,
		confirmText: '去登录',
		success: res => {
			if (res.confirm) {
				uni.redirectTo({
					url: `/pages/park/login/index`
				})
			} else if (res.cancel) {

			}
		}
	})

}

/**跳转登录并返回之前页面*/
export function goLoginReturnOriginalPath() {
	showModal({
		title: '登录',
		content: '立即去登录',
		showCancel: true,
		confirmText: '去登录',
		success: res => {
			if (res.confirm) {
				let curPage = getCurrentPages()
				let route = curPage[curPage.length - 1].route //获取当前页面的路由
				let params = curPage[curPage.length - 1].options //获取当前页面参数，如果有则返回参数的对象，没有参数返回空对象{}
				let query = ''
				let keys = Object.keys(params) //获取对象的key 返回对象key的数组
				if (keys.length > 0) {
					query = keys.reduce((pre, cur) => {
						return pre + cur + '=' + params[cur] + '&'
					}, '?').slice(0, -1)
				}
				console.log(route + query) 
				let path = route + query
				uni.setStorageSync('LOGIN_JUMP_RETURN_PATH',path)
				uni.redirectTo({
					url: `/pages/park/login/index`
				})
			} else if (res.cancel) {
				console.log('取消了....')
			}
		}
	})
}

// 上传图片 - 单张照片上传
export function commonUploadImg(callback) {
	uni.chooseImage({
		count: 1,
		success: res => {
			const tempFilePaths = res.tempFilePaths
			showLoading()
			uni.uploadFile({
				url: uploadFile,
				filePath: tempFilePaths[0],
				name: 'file',
				header: {
					accessToken: getStorageSync('accessToken') || '',
					appToken: getStorageSync('appToken') || '',
					// 'content-type': 'application/x-www-form-urlencoded',
					'content-type': 'multipart/form-data',
					'tenant-id': getStorageSync('TENANT_ID') || config.header['tenant-id']
				},
				formData: {
					name: 'file', // 后端接口要求的名称
					path: uploadPath
					// file: tempFilePath   // 这里一定不能加 file 加了 iOS 图片上传会失败 安卓无此问题
				},
				success: res => {
					callback(res)
				},
				fail: err => {
					console.log(err)
				}
			})
		}, fail: err => {
			console.log(err)
			uni.hideLoading()
		}
	})
}

// 上传视频/图片
export function vedioUploadImg(callback) {
	uni.chooseMedia({
		count: 9,
		mediaType: ['image', 'video'],
		sourceType: ['album', 'camera'],
		maxDuration: 30,
		camera: 'back',
		success: res => {
			const tempFiles = res.tempFiles
			console.log(tempFiles,'tempFiless');
			// 上传图片不大于10mb
			let flag = false
			tempFiles.forEach(v => {
				if (v.size > 10485760) {
					flag = true
				}
			})
			if (flag) {
				uni.showToast({
					title: "上传图片大小不能超过6MB",
					icon: 'error'
				})
				return
			}
			showLoading()
			tempFiles.forEach(item => {
				uni.uploadFile({
					url: uploadFile,
					filePath: item.tempFilePath,
					name: 'file',
					header: {
						Authorization: 'Bearer ' + getStorageSync('ACCESS_TOKEN') || '',
						// 'content-type': 'application/x-www-form-urlencoded',
						'content-type': 'multipart/form-data',
						'tenant-id': getStorageSync('TENANT_ID') || config.header['tenant-id']
					},
					formData: {
						name: 'file', // 后端接口要求的名称
						path: uploadPath
						// path:'imgs/123456789.png',
						// file: tempFilePath   // 这里一定不能加 file 加了 iOS 图片上传会失败 安卓无此问题
					},
					success: res => {
						callback(res)
					},
					fail: err => {
						console.log(err)
					}
				})
			})
			// uni.uploadFile({
			// 	url: uploadFile,
			// 	filePath: tempFiles[0].tempFilePath,
			// 	name: 'file',
			// 	header: {
			// 		Authorization: 'Bearer ' + getStorageSync('ACCESS_TOKEN') || '',
			// 		// 'content-type': 'application/x-www-form-urlencoded',
			// 		'content-type': 'multipart/form-data',
			// 		'tenant-id': getStorageSync('TENANT_ID') || config.header['tenant-id']
			// 	},
			// 	formData: {
			// 		name: 'file', // 后端接口要求的名称
			// 		path: uploadPath
			// 		// path:'imgs/123456789.png',
			// 		// file: tempFilePath   // 这里一定不能加 file 加了 iOS 图片上传会失败 安卓无此问题
			// 	},
			// 	success: res => {
			// 		callback(res)
			// 	},
			// 	fail: err => {
			// 		console.log(err)
			// 	}
			// })
		}, fail: err => {
			console.log(err)
			uni.hideLoading()
		}
	})
}

export function uniUploadFile(path, callback) {
	uni.uploadFile({
		url: uploadFile,
		filePath: path,
		name: 'file',
		header: {
			accessToken: getStorageSync('accessToken') || '',
			// 'content-type': 'application/x-www-form-urlencoded',
			'content-type': 'multipart/form-data',
			'tenant-id': getStorageSync('TENANT_ID') || config.header['tenant-id']
		},
		formData: {
			name: 'file' // 后端接口要求的名称
			// file: tempFilePath   // 这里一定不能加 file 加了 iOS 图片上传会失败 安卓无此问题
		},
		success: res => {
			callback(res)
		},
		fail: err => {
			console.log(err)
		}
	})
}
export function base64Img(url, callback) {
	wx.request({
		url: url,
		method: 'get',
		// ArrayBuffer代表内存之中的一段二进制数据，一旦生成不能再改。可以通过视图（TypedArray和DataView）进行操作。
		responseType: 'arraybuffer',
		success(res) {
			let base64Url = 'data:image/png;base64,' + wx.arrayBufferToBase64(res.data)
			callback(base64Url)
		}
	})
}

// 设置系统亮度
export function setSystemBrightness(val) {
	uni.setScreenBrightness({
		value: val,
		success: function () {
			console.log('success')
		}
	})
}

// 获取系统亮度
export function getSystemBrightness(callback) {
	uni.getScreenBrightness({
		success: function (res) {
			console.log('屏幕亮度值：' + res.value)
			callback(res.value)
		}
	})
}

// 获取原来的系统亮度
export function getSystemBrightnessOld(callback) {
	let osName = getSystemOsName()
	if(osName == 'ios' || osName == 'macos') {
		getSystemBrightness(v => {
			callback(v)
		})
	}else{
		// android
		callback(-1)
	}
}

// 获取运行系统名称 例如：android，ios，macos，windows
export function getSystemOsName() {
	let osName = ''

	uni.getSystemInfo({
		success: function (res) {
			osName = res.osName
		}
	})

	return osName
}

/**文件下载
 * @param filePath 下载文件地址
 * @param callback 回调
*/
export function downloadsFun(myfile,callback){
	uni.showLoading({
		title: '正在下载……'
	})
	wx.downloadFile({
		url: myfile, // 下载url
		success (res) {
		console.log('ressss',res)
		if(res.statusCode == 200) {
			//隐藏加载框
			uni.hideLoading()
			console.log('res.statusCode',res)
			wx.shareFileMessage({
					filePath: res.tempFilePath,
					success(data) {
						console.log('转发成功！！！',data)
						uni.showToast({
							icon: 'success',
							mask: true,
							title: '转发成功',
							duration: 2000,
						})
						callback()
					},
					// fileName:'自定义文件名字.xlsx',
					fail: console.error,
			})
		}
		},
		// fileName:'导出的文件名',
		fail: console.error,
	})
}

/**文件预览
 * @param myfile 文件预览地址
*/
export function openDocumentFile(myfile, fileType){
	uni.showLoading({
		title: '正在打开...'
	})
	uni.downloadFile({
			url: myfile,
			success: function (res) {
				wx.getFileSystemManager().saveFile({
					tempFilePath: res.tempFilePath,
					success: function (ret) {
						// 照片预览
						let imageList = ['jpg', 'jpeg', 'png', 'gif']
						if (imageList.includes(fileType)) {
								uni.hideLoading()
								previewImage([ret.savedFilePath])
							return
						}

						// 文件预览
						openDocument(ret.savedFilePath)
					},
					fail: function(err){
						console.log(err, '保存失败');
						uni.hideLoading()
						uni.$u.toast('暂不支持打开该格式文档')
					}
				}
				)
			}
	})
}

/**文件预览*/
export function openDocument(fileUrl) {
	uni.openDocument({
		showMenu: true,
		filePath: fileUrl,
		success: function (ret) {
			console.log('打开文档成功2');
			uni.hideLoading()
		},
		fail: function(err){
			console.log(err, '打开失败');
			uni.hideLoading()
			uni.$u.toast('暂不支持打开该格式文档')
		}
	})
}

/**照片预览*/
export function previewImage(imagesUrl) {
	uni.previewImage({
		current: 0,
		urls: imagesUrl,
	})
}

/**消息订阅提示
 * @params  @typedef Array<string> tmplIds  消息订阅id 
 * @param @typedef function callback回调函数
*/
export function requestSubscribeMessage(tmplIds,callback) {
	uni.requestSubscribeMessage({
		tmplIds,
		complete (res) { 
			console.log(res);
			callback()
		}
	})
}

